package com.eden.manage.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.eden.manage.dto.PlatDto;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.agent.AgentDto;
import com.eden.manage.mapper.EdenPlatAgentInfoMapper;
import com.eden.manage.mapper.EdenPlatMapper;
import com.eden.manage.mapper.UserInfoMapper;
import com.eden.manage.model.UserInfo;
import com.eden.manage.utils.LoginUtils;
import com.eden.manage.utils.mapstruct.LoginStructUtils;
import eden.api.common.enums.UserTypeEnum;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginService {

    private final UserInfoMapper userInfoMapper;

    private final EdenPlatMapper edenPlatMapper;

    private final EdenPlatAgentInfoMapper platAgentInfoMapper;

    /**
     * 登录接口
     * @param account 账户
     * @param password 密码
     * @return 返回token
     */
    @Transactional(rollbackFor = Exception.class)
    public String login(String account,String password){
        UserInfo userInfo = userInfoMapper.selectUserByAccount(account);
        if(userInfo == null){
            throw new RuntimeException(ErrorEnums.PWD_ERROR.name());
        }
        String pwdUser = DigestUtil.md5Hex(password);
        if(!pwdUser.equals(userInfo.getUserPassword())){
            throw new RuntimeException(ErrorEnums.PWD_ERROR.name());
        }
        String source = String.format(LoginUtils.loginTokenKey, userInfo.getUserAccount(), userInfo.getUserPassword());
        String token = LoginUtils.generateToken(source);
        userInfoMapper.updateToken(account,token);
        return token;
    }

    public UserInfoDto getUserInfo(String token){
        UserInfo userInfo = userInfoMapper.selectUserByToken(token);
        UserInfoDto userInfoDto = LoginStructUtils.INSTANCE.convertUserToDto(userInfo);
        if(userInfoDto.getType().equals(UserTypeEnum.PLAT.getCode())){
            PlatDto platDto = edenPlatMapper.selectPlatById(userInfoDto.getPlatId());
            userInfoDto.setPlatDto(platDto);
        }else if(userInfoDto.getType().equals(UserTypeEnum.AGENT.getCode())){
            AgentDto agentDto = platAgentInfoMapper.selectById(userInfo.getAgentId());
            userInfoDto.setAgentDto(agentDto);
        }
        return userInfoDto;
    }




}
